package gstudio.views;

import java.io.File;
import java.util.List;

import gstudio.data.DataIO;
import gstudio.data.IData;
import gstudio.data.RuntimeDataManager;
import gstudio.data.Text2Satz;
import gstudio.format.StyleManager;
import gstudio.mp3.MiniPlayerComposite;
import gstudio.mp3.Mp3CutTableComposite;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetAdapter;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.part.ViewPart;

public class Artikel_Content extends ViewPart implements
		IPropertyChangeListener, IViewToSave {

	private StyledText styledText;
	private Text titleText;
	private Composite mainComp;
	private IData currentArtikel;
	private MiniPlayerComposite miniPlayer;
	private Label mp3Label;

	private PropertyListenerManager propertyListenerManager = PropertyListenerManager
			.getInstance();

	@Override
	public void createPartControl(Composite parent) {
		currentArtikel = RuntimeDataManager.getInstance().getCurrentData();

		propertyListenerManager.register(this);
		propertyListenerManager.registerSaveAction(this);

		mainComp = new Composite(parent, SWT.NONE);
		{
			GridLayout layout = new GridLayout();
			layout.marginHeight = 10;
			layout.marginWidth = 10;
			mainComp.setLayout(layout);
			mainComp.setBackground(new Color(null, new RGB(179, 187, 217)));
		}

		// 定义控件
		setTitleControl();
		setStyleTextControl();
		setFootComp();

		if (currentArtikel != null) {
			refresh(currentArtikel);
		} else {
			mainComp.setEnabled(false);
		}

		StyleManager.getInstance().setEditorToolBar(this, styledText);
	}

	private String getMp3File(boolean absolutePath) {
		if (currentArtikel == null)
			return "";

		String fileName = currentArtikel.getValueOf("mp3").trim();

		File file = new File(fileName);
		if (file.exists() && file.canRead()) {
			if (!absolutePath) {
				return file.getName();
			} else {
				return file.getAbsolutePath();
			}
		}

		return "";
	}

	@Override
	public void propertyChange(PropertyChangeEvent event) {
		Object obj = event.getNewValue();
		if (obj instanceof IData) {
			refresh((IData) obj);
		}
		mainComp.setEnabled(true);
	}

	// 切换的时候
	private void refresh(IData artikel) {
		currentArtikel = artikel;
		titleText.setText(artikel.getValueOf("title"));
		String mp3Name = getMp3File(false);
		if (mp3Name != null && mp3Label != null) {
			mp3Label.setText(mp3Name);
		}
		String text = artikel.getValueOf("content");
		StyleManager.getInstance().setStyledText(styledText, text);

	}

	/*
	 * 点击文章列表，mp3不应该终止，而是继续播放，除非刷新
	 */
	private void resetMp3CompStatus() {
		if (currentArtikel != null) {
			if (miniPlayer != null) {
				miniPlayer.doStop();
			}
			String fileName = getMp3File(true);

			if (fileName != null && fileName.contains(".mp3")) {
				miniPlayer.getPlayButton().setEnabled(true);
				miniPlayer.setInput(fileName, false);
				miniPlayer.run();
			} else {
				miniPlayer.getPlayButton().setEnabled(false);
			}
		}
	}

	@Override
	public void setFocus() {
	}

	private void setFootComp() {
		Composite footComp = new Composite(mainComp, SWT.NONE);
		{
			GridData gd = new GridData(GridData.FILL_HORIZONTAL);
			footComp.setLayoutData(gd);
			GridLayout gl = new GridLayout(5, false);
			gl.marginHeight = 0;
			gl.marginWidth = 0;
			footComp.setLayout(gl);
		}
		// 刷新按钮
		Button button = new Button(footComp, SWT.NONE);
		button.setText("Refresh");
		button.addListener(SWT.Selection, new Listener() {
			public void handleEvent(Event event) {
				resetMp3CompStatus();
			}

		});

		// 播放器
		miniPlayer = new MiniPlayerComposite(footComp, SWT.NONE);
		miniPlayer.setLayoutData(new GridData());
		resetMp3CompStatus();

		mp3Label = new Label(footComp, SWT.NONE);
		mp3Label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

		// 打开自动断句的窗口
		Button createSatzListButton = new Button(footComp, SWT.NONE);
		createSatzListButton.setText(" Spliter ");
		createSatzListButton.addListener(SWT.Selection, new Listener() {
			@Override
			public void handleEvent(Event arg0) {
				String fileName = getMp3File(true);
				Shell s = new Shell(Display.getCurrent());
				s.setLayout(new GridLayout());

				// 这个播放器作为第一次分割用
				MiniPlayerComposite miniForCut = new MiniPlayerComposite(s,
						SWT.NONE);
				miniForCut.setLayoutData(new GridData());
				miniForCut.setInput(fileName, true);
				miniForCut.setOuputDir(DataIO.getInstance().getTempDir());
				miniForCut.setOuputPreName("p");
				miniForCut.run();

				Mp3CutTableComposite mtc = new Mp3CutTableComposite(s, SWT.NONE);
				miniForCut.setParentObject(mtc);

				mtc.setLayoutData(new GridData(GridData.FILL_BOTH));
				Text2Satz ts = new Text2Satz();
				List<String> list = ts.getSatzList(styledText.getText());
				mtc.setSatzInput(list);
				mtc.setText(titleText.getText(),styledText.getText());
				s.layout();
				s.open();

			}

		});

		DropTarget target = new DropTarget(footComp, DND.DROP_MOVE
				| DND.DROP_COPY | DND.DROP_DEFAULT);
		target.setTransfer(new Transfer[] { FileTransfer.getInstance() });
		target.addDropListener(new DropTargetAdapter() {
			public void dragEnter(DropTargetEvent event) {
			}

			public void drop(DropTargetEvent event) {
				String[] data = (String[]) event.data;
				String fileName = data[0];

				if (fileName.endsWith(".mp3")) {
					File f1 = new File(fileName);

					String newFileName = titleText.getText() + ".mp3";
					newFileName = DataIO.getInstance().getMp3Dir() + "/"
							+ newFileName;

					File f2 = new File(newFileName);

					if (DataIO.getInstance().copyFile(f1, f2)) {
						mp3Label.setText(f2.getName());
						currentArtikel.setValueOf("mp3", newFileName);
						miniPlayer.getPlayButton().setEnabled(true);
						miniPlayer.setInput(newFileName, false);
						miniPlayer.run();
					} else {
						MessageDialog.openError(null, "", newFileName);

					}
				}
			}
		});
	}

	private void setStyleTextControl() {
		styledText = StyleManager.getInstance().getStyleTextControl(mainComp);
		// styledText = new StyledText(mainComp, SWT.MULTI | SWT.WRAP
		// | SWT.V_SCROLL);
		// styledText.setMargins(10, 10, 10, 10);
		// {
		// GridData gd = new GridData(GridData.FILL_BOTH);
		// styledText.setLayoutData(gd);
		// }
		// {
		// FontData[] fontData = new FontData[] { new FontData("Arial", 11,
		// SWT.NORMAL) };
		// styledText.setFont(new Font(null, fontData));
		// }
		styledText.addListener(SWT.FocusOut, new Listener() {
			@Override
			public void handleEvent(Event e) {
				viewDoSave();
			}
		});
	}

	private void setTitleControl() {
		titleText = new Text(mainComp, SWT.BORDER);
		{
			GridData gd = new GridData(GridData.FILL_HORIZONTAL);
			titleText.setLayoutData(gd);
		}
		titleText.addListener(SWT.FocusOut, new Listener() {
			@Override
			public void handleEvent(Event e) {
				if (currentArtikel == null)
					return;
				currentArtikel.setValueOf("title", titleText.getText());
				propertyListenerManager.sendChangeMeassage("updateArtikel",
						currentArtikel);
			}
		});

		{
			FontData[] fontData = new FontData[] { new FontData("Arial", 12,
					SWT.NORMAL) };
			titleText.setFont(new Font(null, fontData));
			titleText.setForeground(Display.getDefault().getSystemColor(
					SWT.COLOR_BLUE));
		}
	}

	// 保存内容 @Override
	public void viewDoSave() {
		StyleManager.getInstance().styledTextSaveToIData(currentArtikel,
				styledText);
	}
}